(function() {
    angular.module('BlurAdmin.pages.SystemSettings')
        .controller('BasicsMCtrl', BasicsMCtrl);

    function BasicsMCtrl(baConfig, $scope, $openModal, $http, $myconfig, $qupload, $log, $mydialog) {


        //默认信息
        $scope.devicesales = { //设备销售网站 信息
            flagshipname: '',
            flagshipurl: '',
            device: [{
                name: "金鼻光",
                url: "",
            }, {
                name: "焕颜宝",
                url: "",
            }]
        }

        $scope.agreement = []; //协议数组对象，

        $scope.todoList = []; //默认第三方

        $scope.app = {
            androiddown: "",
            iosdown: "",
            name: "",
            version: "",
        }


        //弹窗框
        $scope.open = $openModal; //创建实例化对象
        function fn(val) { //关闭模态框方法
            $scope.myopen.opt_close = val;
        }

        $scope.myopen = function(page, size) { //打开模态框
            $scope.open.newOpen(page, size, $scope, fn, 'static');
        }


        //获取系统信息
        $http.get($myconfig.api.app_list_APP).then(function(res) {
            if (res.data.success) {
                console.log(res);
                res.data.data.app && ($scope.app = res.data.data.app); //app信息
                res.data.data.agreement && ($scope.agreement = res.data.data.agreement); //协议信息
                res.data.data.devicesales && ($scope.devicesales = res.data.data.devicesales); //设备信息
                res.data.data.thirdpartyapp && ($scope.todoList = res.data.data.thirdpartyapp);
            }
        });


        //点击发送修改信息
        $scope.modify = function(val, num) {
            var opt = {};
            val == 'app' && (opt.app = $scope.app);
            val == 'devic' && (opt.devicesales = $scope.devicesales);
            val == 'agreement' && (opt.agreement = $scope.agreement);
            val == "thirdpartyapp" && (opt.thirdpartyapp = $scope.todoList);
            $http.post($myconfig.api.app_update_APP, opt).then(function(res) {
                if (res.data.success) {
                    if (num != 1) {
                        $mydialog.success('设置成功');
                        $scope.thirdpartyapp_ste = false;
                    }
                    $scope.myopen.opt_close();
                } else {
                    $mydialog.fail(res.data.data)
                }
            });
        };

        //编辑单条信息
        $scope.bianji_fn = function(val, s) {
            /* app信息 */
            val == 'app' && s == "a" && ($scope.app_s.a = $scope.app_s.a ? false : true);
            val == 'app' && s == "b" && ($scope.app_s.b = $scope.app_s.b ? false : true);
            val == 'app' && s == "c" && ($scope.app_s.c = $scope.app_s.c ? false : true);
            val == 'app' && s == "d" && ($scope.app_s.d = $scope.app_s.d ? false : true);
            /* 设备销售网站 信息 */
            val == 'devic' && s == "a" && ($scope.devic.a = $scope.devic.a ? false : true);
            val == 'devic' && s == "b" && ($scope.devic.b = $scope.devic.b ? false : true);
            val == 'devic' && s == "c" && ($scope.devic.c = $scope.devic.c ? false : true);
            val == 'devic' && s == "d" && ($scope.devic.d = $scope.devic.d ? false : true);
            val == 'devic' && s == "e" && ($scope.devic.e = $scope.devic.e ? false : true);
            val == 'devic' && s == "f" && ($scope.devic.f = $scope.devic.f ? false : true);
            if (!$scope.app_s.a && !$scope.app_s.b && !$scope.app_s.c && !$scope.app_s.d && !$scope.devic.a && !$scope.devic.b && !$scope.devic.c && !$scope.devic.d && !$scope.devic.e && !$scope.devic.f) {
                $scope.modify(val, 0);
            }
        };


        //app设置显示隐藏
        $scope.app_s = {
            a: false,
            b: false,
            c: false,
            d: false
        }

        $scope.app = { // app 信息
            "name": "",
            "version": "",
            "iosdown": "",
            "androiddown": ""
        }

        //设备销售网站
        $scope.devic = {
            a: false,
            b: false,
            c: false,
            d: false
        }



        /* 协议部分 */

        $scope.agreement_index = null; //所在数组的位置

        $scope.set_agreement = function(index, opt) { //点击编辑或者新增
            var agreement_opt = {
                code: '',
                name: '',
                describe: ''
            };
            var optrr = opt ? JSON.stringify(opt) : null;
            $scope.agreement_opt = opt ? JSON.parse(optrr) : agreement_opt; //有值则编辑，没有则新增
            $scope.agreement_index = (index || index == 0) ? index : null;
            $scope.myopen('app/pages/SystemSettings/Basics/Agreement/newAgreement.html', 'lg');
        }

        //删除协议
        function my_callback(val) {
            if (val == true) {
                $scope.agreement.splice($scope.delete_agreement_num, 1);
                $scope.modify('agreement', 0);
            }
        };
        $scope.delete_agreement_num = null;
        $scope.delete_agreement = function(index) {
            $scope.delete_agreement_num = index;
            $mydialog.inquiry('确定要删除吗？', my_callback);
        }

        //完成编辑或者新增
        $scope.complete_agreement = function() {

            if (!$scope.agreement_opt.code) {
                return $mydialog.fail('请填写协议编码')
            }
            if (!$scope.agreement_opt.name) {
                return $mydialog.fail('请填写协议名称')
            }
            if (!$scope.agreement_opt.describe) {
                return $mydialog.fail('请填写内容')
            }
            fasong();
        }

        function fasong() {
            var opt = JSON.stringify($scope.agreement_opt);

            console.log($scope.agreement_index instanceof Number);
            if ($scope.agreement_index !== null) { //有值为编辑，没有为新增
                $scope.agreement[$scope.agreement_index] = JSON.parse(opt);
            } else {
                $scope.agreement.push(JSON.parse(opt));
            }

            $scope.modify('agreement', 0);

        }


        // 获取七牛touken
        function qi_t() {

            $http.get($myconfig.api.QiNiu_token).then(function(res) {
                console.log(res);
                $scope.qi_token_mun = res.data.token;
                $scope.qi_key = res.data.key;
            })
        }
        qi_t();
        //七牛图片上传
        $scope.selectFiles = [];
        //判断是新增第三方图片 还是协议上传图片
        var img_type = null; //1为文本框 2为第三方
        var start = function(index) {
            $scope.selectFiles[index].progress = {
                p: 0
            };
            $scope.selectFiles[index].upload = $qupload.upload({
                key: $scope.qi_key,
                file: $scope.selectFiles[index].file,
                token: $scope.qi_token_mun
            });
            $scope.selectFiles[index].upload.then(function(response) {
                $log.info(response);
                var url = $myconfig.api.Qiniu_url + response.key;
                //插入富文本框
                if (img_type == 1) { //1为文本框 2为第三方
                    $('#summernote').summernote('insertImage', url);
                } else {
                    $scope.thirdpartyapp_data.logo = url;
                }
                qi_t()
            }, function(response) {
                // upload failure
                $log.info(response);
            }, function(evt) {
                // progress
                //evt.totalSize文件大小
                // evt.loaded已上传多少
                var mum = Math.floor(100 * evt.loaded / evt.totalSize);
                //  $scope.context_img == 1 ? ($scope.mystyle.posters.width = mum + '%') : ($scope.mystyle.mainpic.width = mum + '%');
                $scope.selectFiles[index].progress.p = Math.floor(100 * evt.loaded / evt.totalSize);


            });
        };
        $scope.abort = function(index) {
            $scope.selectFiles[index].upload.abort();
            $scope.selectFiles.splice(index, 1);
        };

        $scope.onFileSelect = function($files) {
            var offsetx = $scope.selectFiles.length;
            for (var i = 0; i < $files.length; i++) {
                $scope.selectFiles[i + offsetx] = {
                    file: $files[i]
                };
                start(i + offsetx);
            }
        };

        /* 七牛图片上传结束 */
        //富文本编辑器
        var HelloButton = function(context) { //自定义图片上传按钮
            var ui = $.summernote.ui;
            var button = ui.button({
                contents: '<span  class="glyphicon glyphicon-picture"></span> 图片',
                tooltip: '图片',
                click: function() {
                    img_type = 1 //1文本框 ，2第三方
                    document.getElementById('asd1').click();
                }
            });

            return button.render(); // return button as jquery object 
        }

        $scope.options = {
            height: 300,
            focus: true,
            airMode: false,
            toolbar: [
                ['headline', ['style']],
                ['style', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']],
                ['textsize', ['fontsize']],
                ['fontclr', ['color']],
                ['alignment', ['ul', 'ol', 'paragraph', 'lineheight']],
                ['height', ['height']],
                ['mybutton', ['hello']]
            ],
            buttons: {
                hello: HelloButton
            }
        };

        $scope.transparent = baConfig.theme.blur;
        var dashboardColors = baConfig.colors.dashboard;
        var colors = [];
        for (var key in dashboardColors) {
            colors.push(dashboardColors[key]);
        }

        function getRandomColor() {
            var i = Math.floor(Math.random() * (colors.length - 1));
            return colors[i];
        }

        $scope.thirdpartyapp_data = { //新增或者修改应用
            logo: "",
            name: "",
            iosurl: "",
            androidurl: ""
        }


        var nnn = 0;
        $scope.$watch('todoList', function(newValue, oldValue) {
            if (nnn > 1) {
                if ($scope.thirdpartyapp_ste) { //新增修改为真，提示用户
                    $scope.modify('thirdpartyapp', 0);
                } else {
                    $scope.modify('thirdpartyapp', 1);
                }
            }
            nnn++;
        }, true);

        var thirdpartyapp_index = null; //数组所在的位置

        $scope.set_thirdpartyapp = function(index, opt) { //点击编辑或者第三方
            img_type = 2;
            var agreement_opt = {
                logo: '',
                name: '',
                iosurl: '',
                androidurl: ''
            };
            var optrr = opt ? JSON.stringify(opt) : null;
            $scope.thirdpartyapp_data = opt ? JSON.parse(optrr) : agreement_opt; //有值则编辑，没有则新增
            thirdpartyapp_index = (index || index == 0) ? index : null;
            $scope.myopen('app/pages/SystemSettings/Basics/dsf/newdsf.html', 'lg');
        }

        //完成编辑或者新增
        $scope.jiance_thirdpartyapp = function() {
            if (!$scope.thirdpartyapp_data.logo) {
                return $mydialog.fail('请填添加logo')
            }
            if (!$scope.thirdpartyapp_data.name) {
                return $mydialog.fail('请填写应用名称')
            }
            if (!$scope.thirdpartyapp_data.iosurl) {
                return $mydialog.fail('请填写应用的ios下载地址')
            }
            if (!$scope.thirdpartyapp_data.androidurl) {
                return $mydialog.fail('请填写应用的android下载地址')
            }
            fasong_thirdpartyapp();
        }

        $scope.thirdpartyapp_ste = false;

        function fasong_thirdpartyapp() {
            $scope.thirdpartyapp_ste = true;
            var opt = JSON.stringify($scope.thirdpartyapp_data);
            if (thirdpartyapp_index !== null) { //有值为编辑，没有为新增
                $scope.todoList[thirdpartyapp_index] = JSON.parse(opt);
            } else {
                $scope.todoList.push(JSON.parse(opt));
            }
        }

        //删除第三方
        function my_callback2(val) {
            if (val == true) {
                $scope.thirdpartyapp_ste = true;
                $scope.todoList.splice($scope.delete_thirdpartyapp_num, 1);
            }
        };
        $scope.delete_thirdpartyapp_num = null;
        $scope.delete_thirdpartyapp = function(index) {
            $scope.delete_thirdpartyapp_num = index;
            $mydialog.inquiry('确定要删除吗？', my_callback2);
        }


        $scope.newTodoText = '';

        $scope.addToDoItem = function(event, clickPlus) {
            if (clickPlus || event.which === 13) {
                $scope.todoList.unshift({
                    text: $scope.newTodoText,
                    color: getRandomColor(),
                });
                $scope.newTodoText = '';
            }
        };




    }
})();